package edu.iiitb.studentinfo.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import edu.iiitb.studentinfo.model.Announcement;
import edu.iiitb.studentinfo.model.Student;
import edu.iiitb.studentinfo.util.DBconn;

public class LoginService {
	
	private DBconn dbconn = null;
	private Connection con = null;
	private PreparedStatement pst = null;
	private Statement stmt = null;
	private ResultSet resultSet = null;
	private String query = null;
	
	
	/* Authenticate user return > 0 = valid user
	 *                   return 0 = invalid user
	 *                   return -1 = database connectivity error
	 */
	public int authenticate(String username, String password) {
		int studentId;
		query = "SELECT studentid, username, password FROM student_credentials WHERE username=? and password=?";
		
		try {
			dbconn = new DBconn();
			con = dbconn.getConnection();
			pst = con.prepareStatement(query);
			pst.setString(1, username);
			pst.setString(2, password);
			resultSet = pst.executeQuery();
			
			boolean records = resultSet.next();
			if (!records) {
				studentId = 0;
			}
			else {	
				studentId = resultSet.getInt("studentid");
			}

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			studentId = -1;
		} finally {
			dbconn.close(resultSet);
			dbconn.close(pst);
			dbconn.close(con);
		}
		
		return studentId;
	}
	
	
	public ArrayList<Announcement> getAllAnnouncements() {
		ArrayList<Announcement> announcements = new ArrayList<Announcement>();
		Announcement an = null;
		query = "SELECT announcementid, announcement FROM student_announcements";
		
		try {
			
			dbconn = new DBconn();
			con = dbconn.getConnection();
			pst = con.prepareStatement(query);
			resultSet = pst.executeQuery();
			
			while(resultSet.next()) {
				an = new Announcement();
				an.setAnnouncementid((int) resultSet.getInt("announcementid"));
				an.setAnnouncement((String) resultSet.getString("announcement"));
				announcements.add(an);
				System.out.println(an.getAnnouncement());
			}
			
		} catch (Exception e) {
			System.out.println("error occured");
			System.out.println(e.getMessage());
		} finally {
			dbconn.close(resultSet);
			dbconn.close(pst);
			dbconn.close(con);
		}
		
		return announcements;
	}
	
}
